package download;

import jakarta.servlet.*;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.*;
import org.apache.commons.fileupload.DefaultFileItemFactory;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

@WebServlet(name = "Servlet", value = "/Servlet")
public class Servlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //判断上传的是普通表单还是带文件的
        if(!ServletFileUpload.isMultipartContent((javax.servlet.http.HttpServletRequest) request)){
            return;//终止方法运行，说明这是一个普通表单
        }
        try {
        //创建上传文件的保存路径，建议在WEB-INF目录下，安全，用户无法直接访问上传文件
        String uploadPath = this.getServletContext().getRealPath("/WEB-INF/upload");
        File uploadfile = new File(uploadPath);
        if(!uploadfile.exists())
        {
            uploadfile.mkdir();//创建这个目录
        }

        //缓存，临时文件
        String tmpPath = this.getServletContext().getRealPath("/WEB-INF/tmp");
        File tmpFile = new File(tmpPath);
        if(!tmpFile.exists()){
            tmpFile.mkdir();//创建临时目录
        }
        //1.创建文件上传工厂
        DiskFileItemFactory factory = new DiskFileItemFactory();
        //通过工厂设置缓冲区
        factory.setSizeThreshold(1024*1024);
        factory.setRepository(tmpFile);
        //2.获取fileupload
        ServletFileUpload upload = new ServletFileUpload(factory);

        //3.处理上传的文件，把前端请求解析，封装成一个fineItem对象

            List<FileItem> fileItems = upload.parseRequest((javax.servlet.http.HttpServletRequest) request);
            for (FileItem fileItem : fileItems) {

            }
            UUID uuid = UUID.randomUUID();
        } catch (FileUploadException e) {
            e.printStackTrace();
        }

    }
}
